﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class SysYcjy_UserBrow : System.Web.UI.Page
{

    string s_where, s_order;
    string curindex = String.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["sTittle"] = "浏览用户";
            DataBrid1();
            DataBrid();
            DataBrid2();
            if (Session["sRole"].ToString() == "管理员")
            {
                DataBrid("");
            }
            else
            {
                DataBrid(string.Format(" where a.jigou = '{0}'", Session["sjigou"].ToString()));
            }
           

        }
        lblOnline.Text = Membership.GetNumberOfUsersOnline().ToString();
    }

    private void DataBrid1()
    {
        string sqlText = " SELECT * FROM [nzd] where type = '角色'";
        this.DropDownList1.DataSource = DbHelper.ExecuteTable(CommandType.Text, sqlText, null);
        this.DropDownList1.DataTextField = "value";
        this.DropDownList1.DataValueField = "value";
        this.DropDownList1.DataBind();
    }

    private void DataBrid()
    {
        string sqlText = "SELECT max(id) as id, [jigou] FROM [account] group by jigou";
        this.DropDownList2.DataSource = DbHelper.ExecuteTable(CommandType.Text, sqlText, null);
        this.DropDownList2.DataTextField = "jigou";
        this.DropDownList2.DataValueField = "jigou";
        this.DropDownList2.DataBind();
    }

    //"SELECT [id],a.[username],[username1],[mail],[city],[gzdw],[jigou],[mobile],[xtsj1] FROM [account] as a inner join [aspnet_users] as b on a.username=b.userName inner join [aspnet_membership] as c on b.userid=c.userid WHERE ((isLockedOut=0 and isApproved=1) and (a.[role] = @role) AND (a.[jigou] = @jigou)) order by id desc"

    //李红新更改 2010-09-17 条件绑定数据
    private void DataBrid(string sqlwhere)
    {
        int record = 0;
        int count = 0;
        s_order = "ORDER BY [id] DESC";
        string sqlText = "[id],a.[username],[username1],[mail],[city],[gzdw],[jigou],[mobile],[xtsj1]";
        DataTable DT = DbHelper.ExecutePage(sqlText, "[account] as a inner join [aspnet_users] as b on a.username=b.userName inner join [aspnet_membership] as c on b.userid=c.userid" + sqlwhere, "id", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView1.DataSource = DT;
        this.GridView1.DataBind();
    }

    private void DataBrid2()
    {
        string sqlWhere = string.Empty;
        if (Session["sRole"] != null && Session["sRole"].ToString() != "管理员")
        {
            DropDownList2.Items.Clear();
            DropDownList2.Items.Insert(0, new ListItem(Session["sjigou"].ToString()));

            //DataBrid(string.Format(" WHERE (isLockedOut=0 and isApproved=1) and a.[role] = '{0}'  and  a.[jigou] = '{1}'", this.DropDownList1.SelectedValue, Session["sjigou"].ToString()));
        }
        //else
        //{
        //    DataBrid(string.Format(" WHERE (isLockedOut=0 and isApproved=1) and a.[role] = '{0}'  and  a.[jigou] = '{1}'", this.DropDownList1.SelectedValue, "远程教育平台"));
        //}
    }





    protected void Button1_Click(object sender, EventArgs e)    //删除用户
    {
        Conn zconn = new Conn();
        int j = 0;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            j = j++;
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
                string zusername = GridView1.Rows[i].Cells[1].Text;
                if (zusername != Session["sUsername"].ToString())   //不允许删除管理员自己.
                {
                    string zsql = "delete from account where username='" + zusername + "'";
                    string zsql1 = "select distinct role from account where username='" + zusername + "'";
                    string zrole = zconn.sqlFirst(zsql1);
                    if (zconn.ExeSql(zsql) == 1)
                    {
                        Membership.DeleteUser(zusername, true);//删除系统数据库中与用户相关的所有数据
                        Roles.RemoveUserFromRole(zusername, zrole);//将该用户从角色中删除
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(GetType(), "deleteError", "alert('删除用户失败,请联系系统管理员');", true);
                    }
                }
            }
        }
        zconn.Dispose();
        DataBrid1();
        DataBrid();
        DataBrid2();
        DataBrid("");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        //重设密码
        int total = 0;
        Random ran = new Random();
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
                string zusername = GridView1.Rows[i].Cells[1].Text;
                MembershipUser zuser = Membership.GetUser(zusername);
                /*2010-5-5 张小林 生成随机密码*/
                char[] pwdChars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                string password = string.Empty;
                for (int y = 0; y < 7; y++)
                {
                    password += pwdChars[ran.Next(pwdChars.Length)];
                }
                string pwd = zuser.ResetPassword();
                zuser.ChangePassword(pwd, password);
                lblMessage.Text += String.Format("用户名:{0} 新密码:{1}<br />", zusername, password);
                total++;
            }
        }
        if (total > 0)
        {
            lblMessage.Text += "上述所选用户的密码已经被重置";
        }
    }
    protected void btnLockUser_Click(object sender, EventArgs e)
    {
        //锁定所选用户并强制该用户下线
        int total = 0;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
                string zusername = GridView1.Rows[i].Cells[1].Text;
                MembershipUser zuser = Membership.GetUser(zusername);
                if (zuser != null)
                {
                    zuser.IsApproved = false;
                    Membership.UpdateUser(zuser);
                    Dictionary<string, string> userList = Application.Get("GLOBAL_USER_LIST") as Dictionary<string, string>;
                    if (userList != null)
                    {
                        string userKey = string.Empty;
                        foreach (var item in userList)
                        {
                            if (item.Value != null && String.Compare(item.Value, zuser.UserName) == 0)
                            {
                                userKey = item.Key;
                                userList[userKey] = "useronline";
                                break;
                            }
                        }
                    }
                    else
                    {
                        userList = new Dictionary<string, string>();
                    }
                    userList[Session.SessionID] = zuser.UserName;
                    Application.Lock();
                    Application.Add("GLOBAL_USER_LIST", userList);
                    Application.UnLock();
                    total++;
                }
            }
        }
        if (total > 0)
        {
            lblMessage.Text = "所选用户已经被禁用";
            DropDownList1_SelectedIndexChanged(sender, e);
        }
    }
    protected void btnUnlock_Click(object sender, EventArgs e)
    {
        //解锁所选用户
        int total = 0;
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
            if (cbox.Checked == true)
            {
                string zusername = GridView1.Rows[i].Cells[1].Text;
                MembershipUser zuser = Membership.GetUser(zusername);
                if (!zuser.IsApproved)
                {
                    zuser.IsApproved = true;
                    Membership.UpdateUser(zuser);
                }
                if (zuser.IsLockedOut)
                {
                    zuser.UnlockUser();
                }
                total++;
            }
        }
        if (total > 0)
        {
            lblMessage.Text = "所选用户已经被解除锁定";
            DropDownList1_SelectedIndexChanged(sender, e);
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string username = e.Row.Cells[1].Text.Trim();
            MembershipUser mu = Membership.GetUser(username);
            if (mu != null && mu.IsApproved && !mu.IsLockedOut)
            {
                e.Row.Cells[4].Text = "正常";
            }
            else
            {
                e.Row.Cells[4].Text = "锁定";
            }
            ////当鼠标停留时更改背景色
            //e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#80BA21'");
            ////当鼠标移开时还原背景色
            //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
    }
    protected void chkIsLocked_CheckedChanged(object sender, EventArgs e)
    {
        getLock();
    }

    private void getLock()
    {
        if (chkIsLocked.Checked)
        {
            DataBrid(string.Format(" where (isLockedOut=1 or isApproved=0) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
        }
        else
        {
            DataBrid(string.Format(" where (isLockedOut=0 or isApproved=1) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
        }
    }


    //搜索条件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        var strWhere = " where 1=1";
        if (!string.IsNullOrEmpty(DropDownList1.SelectedValue))
        {
            strWhere += " and a.role='" + DropDownList1.SelectedValue + "'";
        }
        if (!string.IsNullOrEmpty(DropDownList2.SelectedValue))
        {
            strWhere += " and a.jigou='" + DropDownList2.SelectedValue + "'";
        }
        if (!string.IsNullOrEmpty(txtUser.Text))
        {
            strWhere += " and a.username like '%" + txtUser.Text + "%'";
        }
        if (!string.IsNullOrEmpty(ShouJi.Text))
        {
            strWhere += " and a.mobile like '%" + ShouJi.Text + "%'";
        }
        if (chkIsLocked.Checked)
        {
            strWhere += " and (isLockedOut=1 or isApproved=0)";
        }
        ViewState["sqlwhere"] = strWhere;
        Pager.CurrentPageIndex = 0;
        DataBrid(strWhere);
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Pager.CurrentPageIndex = 0;
        if (chkIsLocked.Checked)
        {
            DataBrid(string.Format(" where (isLockedOut=1 or isApproved=0) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
            ViewState["sqlwhere"] = string.Format(" where (isLockedOut=1 or isApproved=0) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue);
        }
        else
        {
            DataBrid(string.Format(" WHERE (isLockedOut=0 and isApproved=1) and (a.[role] = '{0}') AND (a.[jigou] = '{1}')", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
            ViewState["sqlwhere"] = string.Format(" WHERE (isLockedOut=0 and isApproved=1) and (a.[role] = '{0}') AND (a.[jigou] = '{1}')", DropDownList1.SelectedValue, DropDownList2.SelectedValue);

        }
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        Pager.CurrentPageIndex = 0;
        if (chkIsLocked.Checked)
        {
            DataBrid(string.Format(" where (isLockedOut=1 or isApproved=0) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
            ViewState["sqlwhere"] = string.Format(" where (isLockedOut=1 or isApproved=0) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue);
        }
        else
        {
            DataBrid(string.Format(" where (isLockedOut=1 or isApproved=1) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue));
            ViewState["sqlwhere"] = string.Format(" where (isLockedOut=1 or isApproved=1) and a.role='{0}' and a.jigou='{1}'", DropDownList1.SelectedValue, DropDownList2.SelectedValue);
        }
    }




    protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        Pager.CurrentPageIndex = e.NewPageIndex;
        if (ViewState["sqlwhere"] != null)
        {
            DataBrid(ViewState["sqlwhere"].ToString());
        }
        else
        {
            DataBrid("");
        }


    }
}
